package com.qf.producer.listeners;

import com.alibaba.fastjson.JSON;
import com.qf.producer.pojo.Order;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@RocketMQTransactionListener(txProducerGroup = "orderTx")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {
    /*
        当半消息主题收到事务消息后，会触发的第一个回调，在这个回调中就去处理上游服务的事务（比如-支付业务）
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(org.springframework.messaging.Message msg, Object arg) {
        //获取的就是消息体内容的自己形式
        byte[] body = (byte[]) msg.getPayload();
        String orderStr = new String(body);

        Order order = JSON.parseObject(orderStr, Order.class);

        System.out.println("executeLocalTransaction....");

        //id为2，模拟这个支付是成功的；id为3模拟是失败的；id为4模拟未知
        if (order.getId() == 2){
            return RocketMQLocalTransactionState.COMMIT;
        }else if (order.getId() == 3){
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        return RocketMQLocalTransactionState.UNKNOWN;
    }

    /*
         当半消息主题收到的是UNKNOW状态时，会触发第二个回调，检查上游服务事务的结果（比如-检查支付的结果）
      */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(org.springframework.messaging.Message msg) {

        System.out.println("check time:" + LocalDateTime.now());

        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
